using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WhereWolf
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}


		private void addFiles()
		{
			DialogResult dlgResult = this.openFileDialog1.ShowDialog();
			if (dlgResult == DialogResult.OK)
			{
				String[] strFilenames = this.openFileDialog1.FileNames;
				foreach (String FullFilename in strFilenames)
				{
					String ShortFilename = Path.GetFileName(FullFilename);
					ListViewItem li = new ListViewItem();
                    li = lvwFiles.Items.Add(ShortFilename, 0);
					li.SubItems.Add(Path.GetFullPath(FullFilename));
				}
			}
		}

		private void btnAddFiles_Click(object sender, EventArgs e)
		{
			addFiles();
		}


		private void copyFiles()
		{
			if (lvwFiles.Items.Count == 0)
			{
				MessageBox.Show("You don't have any files to copy.");

			}
			else
			{
				if (lvwDestinations.Items.Count == 0)
				{
					MessageBox.Show("You haven't specified any folders to copy your files to.");
				}
				else
				{
					DialogResult dlgResult = MessageBox.Show("Are you sure you want to copy these files?", "Copy Files", MessageBoxButtons.YesNo);
					if (dlgResult == DialogResult.Yes)
					{
						// Setup the progress bar
						this.toolStripProgressBar1.Visible = true;
						this.toolStripProgressBar1.Maximum = (lvwFiles.Items.Count * lvwDestinations.Items.Count);

						foreach (ListViewItem li in lvwFiles.Items)
						{
							String SourcePath = li.SubItems[1].Text;

							foreach (ListViewItem liDir in lvwDestinations.Items)
							{
								try
								{
									String DestinationPath = liDir.Text + "\\" + li.Text;
									File.Copy(SourcePath, DestinationPath, true);
									
									this.toolStripProgressBar1.PerformStep();
									this.toolStripStatusLabel1.Text = String.Format("Copying {0} to {1}", li.SubItems[0].Text, DestinationPath);
									this.statusStrip1.Refresh();
								}
								catch (Exception)
								{
									MessageBox.Show("There was an error copying " + SourcePath + ".");
								}
							}
						}

						
						MessageBox.Show("All files copied successfully.");

						this.toolStripStatusLabel1.Text = "";
						this.toolStripProgressBar1.Value = 0;
						this.toolStripProgressBar1.Visible = false;
					}
				}
			}
		}


		private void btnCopy_Click(object sender, EventArgs e)
		{
			copyFiles();
		}


		private void ReloadProfiles()
		{
			cboProfiles.Items.Clear();

			cboProfiles.Items.Add("< New Profile >");

			try
			{
				System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
				xml.Load(Application.StartupPath + "\\Profiles.xml");

				foreach (System.Xml.XmlNode profileNode in xml.SelectNodes("//PROFILES/PROFILE"))
				{
					try
					{
						String strProfileName = profileNode.SelectSingleNode("@ID").Value;
						cboProfiles.Items.Add(strProfileName);
					}
					catch (Exception err)
					{
						MessageBox.Show("Failed reading xml: " + err.Message);
						throw;
					}
				}
			}
			catch (Exception)
			{
				// Create the Profiles.xml and try again
				using (StreamWriter sw = new StreamWriter(Application.StartupPath + "\\Profiles.xml", true))
				{
					sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?><PROFILES></PROFILES>");
				}

				ReloadProfiles();
			}
		}


		private void Form1_Load(object sender, EventArgs e)
		{
			ReloadProfiles();
		}


		private void cboProfiles_SelectedIndexChanged(object sender, EventArgs e)
		{
			lvwDestinations.Items.Clear();

			System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
			xml.Load(Application.StartupPath + "\\Profiles.xml");

			foreach (System.Xml.XmlNode profileNode in xml.SelectNodes("//PROFILES/PROFILE[@ID='" + cboProfiles.SelectedItem.ToString() + "']"))
			{
				foreach (System.Xml.XmlNode folderNode in profileNode.SelectNodes("Folder"))
				{
					String strFolderName = folderNode.SelectSingleNode("@Path").Value;
					ListViewItem li = new ListViewItem();
					li = lvwDestinations.Items.Add(strFolderName, 0);
				}
			}
		}

		
		private void exitToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.Close();
		}


		private void deleteCurrentProfile()
		{
			// Get the current profile name
			string ProfileName;
			try
			{
				ProfileName = cboProfiles.Text.Replace("\"", "").Trim();

				DialogResult dlgResult = MessageBox.Show("Are you sure you want to delete the \"" + ProfileName + "\" profile?", "Delete Current Profile", MessageBoxButtons.YesNo);
				if (dlgResult == DialogResult.Yes)
				{
					System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
					xml.Load(Application.StartupPath + "\\Profiles.xml");

					// Remove all the folders in the selected profile
					try
					{
						System.Xml.XmlNode profileNode = xml.SelectSingleNode("//PROFILES/PROFILE[@ID='" + cboProfiles.SelectedItem.ToString() + "']");
						profileNode.ParentNode.RemoveChild(profileNode);
					}
					catch (Exception)
					{
						// Do nothing
					}

					// Save the new XML
					xml.Save("Profiles.xml");

					lvwDestinations.Items.Clear();
					cboProfiles.Text = "";

					// Reload profile list
					ReloadProfiles();
				}
			}
			catch (Exception)
			{
				ProfileName = "";
				throw;
			}
		}


		// Saves the current profile
		private void saveCurrentProfile()
		{
			// Get the current profile name
			// If it's <New Profile> then ask for a new name
			string ProfileName;
			try
			{
				ProfileName = cboProfiles.Text;
			}
			catch (Exception)
			{
				ProfileName = "";
				throw;
			}

			ProfileName = ProfileName.Replace("\"", "").Trim();

			if ((ProfileName == "< New Profile >") || (ProfileName == ""))
			{
				MessageBox.Show("Please type a name for this profile.");
				cboProfiles.Focus();
			}
			else
			{
				System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
				xml.Load(Application.StartupPath + "\\Profiles.xml");

				// Remove all the folders in the selected profile
				try
				{
					System.Xml.XmlNode profileNode = xml.SelectSingleNode("//PROFILES/PROFILE[@ID='" + cboProfiles.SelectedItem.ToString() + "']");
					profileNode.ParentNode.RemoveChild(profileNode);
				}
				catch (Exception)
				{
					// Do nothing
				}

				// Add the selected profile to the xml
				String strNewXML = "<PROFILE ID=\"" + ProfileName + "\">";

				// Loop through all the folders in the destination listview
				// and add them to the selected profile
				foreach (ListViewItem liDir in lvwDestinations.Items)
				{
					if (liDir.Text.Trim() != "")
					{
						strNewXML += "<Folder Path=\"" + liDir.Text + "\" />";
					}
				}

				strNewXML += "</PROFILE>";

				System.Xml.XmlDocumentFragment docFrag = xml.CreateDocumentFragment();
				docFrag.InnerXml = strNewXML;

				System.Xml.XmlNode masterProfileNode = xml.SelectSingleNode("//PROFILES");
				masterProfileNode.AppendChild(docFrag);

				// Save the new XML
				xml.Save(Application.StartupPath + "\\Profiles.xml");

				MessageBox.Show("Profile saved.");

				// Reload profile list
				ReloadProfiles();
			}
		}



		private void AboutToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Version vrs = new Version(Application.ProductVersion);
			MessageBox.Show("Written by Dave Haynes\r\n\r\nProvided by Downcast Systems\r\n\r\nVersion: " + vrs.Major.ToString() + "." + vrs.Minor.ToString() + "." + vrs.Build.ToString() + "." + vrs.Revision.ToString());
		}

		// ------------- Adding Folders --------------
		private void addMultipleFolders()
		{
			WhereWolf.frmFolderPicker frmFP = new WhereWolf.frmFolderPicker();
			DialogResult dlgResult = frmFP.ShowDialog();
			if (dlgResult == DialogResult.OK)
			{
				foreach (String subDir in frmFP.SelectedDirectories)
				{
					lvwDestinations.Items.Add(subDir, 0);
				}
			}
		}


		private void btnAddDestinations_Click(object sender, EventArgs e)
		{
			addMultipleFolders();
		}


		private void addFolderToolStripMenuItem_Click(object sender, EventArgs e)
		{
			addMultipleFolders();
		}

		private void ctxRemoveFolder_Click(object sender, EventArgs e)
		{
			foreach (ListViewItem li in lvwDestinations.SelectedItems)
			{
				lvwDestinations.Items.Remove(li);
			}
		}

		private void ctxRemoveFiles_Click(object sender, EventArgs e)
		{
			foreach (ListViewItem li in lvwFiles.SelectedItems)
			{
				lvwFiles.Items.Remove(li);
			}
		}

		private void ctxAddFolders_Click(object sender, EventArgs e)
		{
			addMultipleFolders();
		}

		private void ctxAddFiles_Click(object sender, EventArgs e)
		{
			addFiles();
		}

		private void mnuCopyFiles_Click(object sender, EventArgs e)
		{
			copyFiles();
		}

		private void saveCurrentProfileToolStripMenuItem_Click(object sender, EventArgs e)
		{
			saveCurrentProfile();
		}

		private void deleteCurrentProfileToolStripMenuItem_Click(object sender, EventArgs e)
		{
			deleteCurrentProfile();
		}

		private void mnuAddFolders_Click(object sender, EventArgs e)
		{
			addMultipleFolders();
		}

		private void mnuAddFiles_Click(object sender, EventArgs e)
		{
			addFiles();
		}

	}
}